package nobnak.study.gl.projection;

import nobnak.study.gl.projection.RasterizationUtil.ProgressListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.AsyncTask;

public class RenderTask {
	private PostProgressListener listner;
	
	public RenderTask(PostProgressListener listener) {
		this.listner = listener;
	}
	
	// Interfaces
	public interface PostProgressListener {
		void onPostProgress(Bitmap result);
	}
	
	// Methods
	public void execute(final int width, final int height, final float[] vpvMatrix, final Triangle[] triangles, Context context) {
		final int total = width * height;
		final ProgressDialog dialog = new ProgressDialog(context);
		dialog.setTitle(context.getString(R.string.title_rasterization_dialog));
		dialog.setMessage(context.getString(R.string.message_rasterization_dialog));
		dialog.setMax(total);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		final AsyncTask<Void, Integer, Bitmap> rasterizationTask = new AsyncTask<Void, Integer, Bitmap>() {
			@Override
			protected Bitmap doInBackground(Void... params) {
				return RasterizationUtil.rasterize(triangles, width, height, vpvMatrix, new ProgressListener() {
					@Override
					public void onStart(int position, int total) {
						publishProgress(position);
					}
					@Override
					public void onEnd(int position, int total) {}
				});
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				dialog.dismiss();
				listner.onPostProgress(result);
			}
			@Override
			protected void onProgressUpdate(Integer... values) {
				dialog.setProgress(values[0]);
			}
			@Override
			protected void onCancelled() {
			}
		}.execute();
		dialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				rasterizationTask.cancel(true);
			}
		});
		dialog.show();
	}
}
